package com.kfm.servlet;

import com.kfm.entity.Classes;
import com.kfm.entity.Student;
import com.kfm.entity.StudentDTO;
import com.kfm.entity.User;
import com.kfm.mapper.IClassesMapper;
import com.kfm.mapper.IStudentMapper;
import com.kfm.service.ClassesService;
import com.kfm.service.IStudentService;
import com.kfm.service.StudentService;
import com.kfm.service.UserService;
import com.kfm.util.Contains;
import com.kfm.util.Page;
import com.kfm.util.UUIDUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private IStudentService service;
    private UserService userService = new UserService();
    private ClassesService classesService;

    @Override
    public void init() throws ServletException {
        ServletContext servletContext = getServletContext();
        Object attribute = servletContext.getAttribute(Contains.SQL_SESSION_FACTORY);

        if (attribute instanceof SqlSessionFactory sqlSessionFactory){

            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            IClassesMapper classesMapper = sqlSession.getMapper(IClassesMapper.class);
            IStudentMapper studentMapper = sqlSession.getMapper(IStudentMapper.class);

            classesService = new ClassesService(classesMapper);
            // 创建 实现类， 和实现类有耦合了
            service = new StudentService(studentMapper);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("t");
        if (type == null || "".equals(type)){
            String page = req.getParameter("page");
            String size = req.getParameter("size");
            // 学生列表页面
            Page<StudentDTO> pageStudentDTO = service.listWithTeacherNameAndClassName(page, size);
            req.setAttribute("pages", pageStudentDTO);
            req.getRequestDispatcher("/WEB-INF/student/index.jsp").forward(req, resp);
        } else if ("add".equals(type)){ // 添加学生
            List<User> allTeacher = userService.findAllTeacher();
            List<Classes> classesList = classesService.findAll();
            req.setAttribute("teachers", allTeacher);
            req.setAttribute("classes", classesList);
            req.getRequestDispatcher("/WEB-INF/student/add.jsp").forward(req, resp);
        } else if ("edit".equals(type)){ // 修改信息
            String id = req.getParameter("id");
            Student student = service.findById(id);
            List<User> allTeacher = userService.findAllTeacher();
            List<Classes> classesList = classesService.findAll();
            req.setAttribute("teachers", allTeacher);
            req.setAttribute("classes", classesList);
            req.setAttribute("student", student);
            req.getRequestDispatcher("/WEB-INF/student/edit.jsp").forward(req, resp);
        } else if ("delete".equals(type)){ // 删除信息
            String id = req.getParameter("id");
            service.delete(id);
            resp.sendRedirect("/student");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String teacher = req.getParameter("teacher");
        String classId = req.getParameter("classId");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        if (birthday != null){
            try {
                parse = sdf.parse(birthday);
            } catch (ParseException e) {
                e.printStackTrace();
                parse = new Date();
            }
        }

        Student stu = new Student();

        stu.setName(name);
        stu.setGender(Integer.parseInt(gender));
        stu.setBirthday(parse);
        stu.setTeacher(teacher);
        stu.setClassId(Integer.parseInt(classId));

        // 新增还是修改
        int row = -1;
        String id = req.getParameter("id");
        if (id == null) {
            // 新增学生
            stu.setId(UUIDUtil.uuid32());
            row = service.save(stu);
        } else{
            // 修改信息
            stu.setId(id);
            row = service.update(stu);
        }

        if ( row > 0 ){
            resp.sendRedirect("/student");
        } else{
            req.setAttribute("msg", "保存失败");
            req.getRequestDispatcher("/WEB-INF/student/index.jsp").forward(req, resp);
        }

    }
}
